package com.epfresh.activity;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.PointerInputFilter;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.MultipleStatusView;
import com.epfresh.api.widget.keyboard.KeyboardUtil;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.R;
import com.epfresh.global.BaseActivity;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.entity.ResponseEntity;
import multitype.MultiTypeAdapter;
import multitype.WrapContentLinearLayoutManager;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

import com.epfresh.adapter.*;
import com.epfresh.bean.*;
import com.epfresh.global.CartHelper;
import com.epfresh.global.DataManager;
import com.epfresh.utils.FormatUtil;
import com.epfresh.views.FakeAddImageView;
import com.epfresh.views.PointFTypeEvaluator;
import com.google.gson.Gson;

/*我的问价*/
public class OfferMyActivity extends BaseActivity {
    private MultipleStatusView msvGoods;
    RecyclerView rvGoods;
    MultiTypeAdapter mGoodsAdapter;
    ViewBinderOfferMy mGoodsBinder;
    LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();
    List<Object> mGoods = new ArrayList<>();

    OfferMyList currentGoods;
    int pageNum = 0;
    private PtrFrameLayout ptrFrameLayout;
    boolean freshFlag = false;

    KeyboardUtil keyboardUtil;
    EditText etInput;
    //键盘页面
    private View llKeyboard;
    //键盘背景
    private View llKeyboardBg;
    View ivOfferClear;

    protected void updateKeyboard() {
        if (!keyboardUtil.isKeyboardShowing()) {
            llKeyboard.setVisibility(View.GONE);
            llKeyboardBg.setVisibility(View.GONE);
            etInput.setVisibility(View.GONE);

        } else {
            llKeyboard.setVisibility(View.VISIBLE);
            llKeyboardBg.setVisibility(View.VISIBLE);
            llKeyboardBg.setBackgroundColor(0x60000000);
            etInput.setText("");
            etInput.setVisibility(View.VISIBLE);
        }
    }

    public void openOfferDialog(final OfferMyList cartGood) {
        //商品数量
        ivOfferClear = findViewById(R.id.iv_offer_clear);
        llKeyboard = findViewById(R.id.ll_keyboard);
        llKeyboardBg = findViewById(R.id.v_keyboard_bg);
        etInput = (EditText) findViewById(R.id.et_input);
        PointerInputFilter cashierInputFilter = new PointerInputFilter();
        cashierInputFilter.MAX_VALUE = 99999.99d;
        etInput.setFilters(new InputFilter[]{cashierInputFilter});
        ivOfferClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etInput.setText("");
            }
        });

        llKeyboardBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyboardUtil.hideKeyboard();
                updateKeyboard();
            }
        });
        keyboardUtil = new KeyboardUtil(this);
        keyboardUtil.attachTo(etInput);

        keyboardUtil.setOnCancelClick(new KeyboardUtil.onCancelClick() {
            @Override
            public void onCancellClick() {
                updateKeyboard();
            }
        });

        keyboardUtil.setOnOkClick(new KeyboardUtil.OnOkClick() {
            @Override
            public void onOkClick() {
                updateKeyboard();
                try {
                    double d = Double.valueOf(etInput.getText().toString());
                    if(d==0){
                        return;
                        //T.toast("问价数量请大于0");
                    }
                    requestOffer(""+d,cartGood);

                    //onCommit(""+d, cartGood);
                } catch (Exception e) {
                    e.printStackTrace();
                    T.toast("请检查输入");
                    keyboardUtil.showKeyboard();
                    updateKeyboard();
                }
            }
        });
        updateKeyboard();
    }

    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rvGoods, header) /*&& !loadMoreDelegate.isLoading()*/;
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            if (!loadMoreDelegate.isLoading()) {
                freshFlag = true;
                reqGoodsList(0);
            } else {
                ptrFrameLayout.refreshComplete();
            }
        }
    };
    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();

            reqGoodsList(pageNum + 1);
        }
    };
    ViewGroup rl_main_layout;
    private void initHeadView() {
        ptrFrameLayout = (PtrFrameLayout) findViewById(R.id.ptr_ff);
        ptrFrameLayout.setPtrHandler(ptrHandler);
        rl_main_layout = (ViewGroup) findViewById(R.id.rl_main_layout);
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offer_my);
        initToolbar();
        initView();
        toolbarTitle.setText("我的问价");
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);
        righticon.setImageResource(R.mipmap.offer_cart);
        righticon.setVisibility(View.VISIBLE);
        righticon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //submit();
                Intent intent = new Intent(OfferMyActivity.this, CartActivity.class);
                startActivity(intent);
            }
        });
        //初始化view
        reqGoodsList(0);
    }

    protected View getToolBar() {

        return null;
    }

    protected void initToolbar() {
        rightbtn = (TextView) findViewById(com.epfresh.api.R.id.rightbtn);
        toolbarTitle = (TextView) findViewById(R.id.toolbar_title);

        righticon = (ImageView) findViewById(com.epfresh.api.R.id.righticon);//
        ivBack = (ImageView) findViewById(com.epfresh.api.R.id.baseback);
        tvBack = (TextView) findViewById(com.epfresh.api.R.id.tv_back);
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivBack.performClick();
            }
        });
        ivBack.setOnClickListener(this);

    }

    private void initView() {

        rvGoods = (RecyclerView) findViewById(R.id.rv_goods);
        msvGoods = (MultipleStatusView) findViewById(R.id.msv_goods);
        msvGoods.setHint("还没有问价商品");
        LinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        msvGoods.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reqGoodsList(0);
            }
        });
        initGoodsView();
    }


    LinearLayoutManager layoutManagerGoods;
    private void initGoodsView() {
        initHeadView();
        rvGoods = (RecyclerView) findViewById(R.id.rv_goods);
        layoutManagerGoods = new WrapContentLinearLayoutManager(this);
        layoutManagerGoods.setOrientation(LinearLayoutManager.VERTICAL);
        rvGoods.setLayoutManager(layoutManagerGoods);
        mGoodsAdapter = new MultiTypeAdapter();
        mGoodsBinder = new ViewBinderOfferMy();
        mGoodsBinder.setOnCartAddListener(new ViewBinderOfferMy.OnCartAddListener() {
            @Override
            public void onCartAdd(int type, int position, OfferMyList goods, View v) {
                if (type == 1) {//购物车手动输入
                    openDialog(goods);
                } else if (type == 2) {//添加
                    addCartCnt(v, goods, true);
                } else if (type == 3) {//减少
                    addCartCnt(v, goods, false);
                } else if (type == 10) {
                    openOfferDialog(goods);
                } else if (type == 5) {
                    String id = goods.getProductId();
                    Intent intent = new Intent(mContext, DetailGoodsActivity.class);
                    intent.putExtra("storeId", goods.getStoreId());
                    intent.putExtra("id", id + "");
                    intent.putExtra("promotionItemId", goods.getPromotionItemId());
                    startActivity(intent);
                }
            }
        });

        mGoodsBinder.setFreshItemListener(new ViewBinderOfferMy.FreshItemListener() {
            @Override
            public void freshItem(int type, int position, OfferMyList goods, View v) {
               requestFreshItem(goods);
            }
        });



        mGoodsAdapter.register(OfferMyList.class, mGoodsBinder);
        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        loadMoreViewBinder.setResourceId(com.epfresh.api.R.layout.common_view_load_more);
        mGoodsAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        rvGoods.setAdapter(mGoodsAdapter);
        mGoodsAdapter.setItems(mGoods);

        loadMoreDelegate.attach(rvGoods, loadMoreSubject);
    }


    public Timer timer;
    boolean isTimerAlive;
    TimerTask task ;
    Handler handler = new Handler(){

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    mGoodsAdapter.notifyDataSetChanged();
                    break;
            }
            super.handleMessage(msg);
        }

    };

    public void timerStart() {
        timerStop();
        if(timer == null)
            timer = new Timer();

        task =  new TimerTask() {
            @Override
            public void run() {
                try {
                    if (isTimerAlive){
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        isTimerAlive = true;

        timer.schedule(task, 0, 1000);
    }


    public void timerStop() {
        isTimerAlive = false;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null){
            task.cancel();
            task = null;
        }
    }



    public void requestOffer(String productCount, final OfferMyList goods) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_offer_addProductOffer);

        re.putParameter("productSpecId", goods.getProductId());
        re.putParameter("quantity", productCount);

        request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_offer_addProductOffer, new OnRequestListener<OfferDtoBean>() {
            @Override
            public OfferDtoBean jsonToObj(String s) {
                return new Gson().fromJson(s, OfferDtoBean.class);
            }

            @Override
            public void onFail(int i, Object o, Object o1) {
                hideProgressDialog();
            }

            @Override
            public void onResponseError(int i, Object o1, Object o) {
                hideProgressDialog();
            }

            @Override
            public void onStart(Object o) {
                showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<OfferDtoBean> responseEntity, Object o) {
                hideProgressDialog();
                OfferDtoBean bean = responseEntity.getResponseElement();
                if(bean.isSuccess()){
                    DataManager.getInstance().oftenListReFresh = true;
                    T.toast("问价已发送");
                    goods.setProductOfferDetailsId(bean.getProductOfferDetailsId());
                    goods.setQuantity(""+bean.getCount());
                    goods.setCreateTime(bean.getCreateTime());
                    goods.setOfferStatusCopy("努力报价中");
                    goods.setStatus(bean.getStatus());
                    mGoodsAdapter.notifyItemChanged(mGoods.indexOf(goods));
                }

            }
        });

    }


    protected void updateGoodsList(ContentEntity<OfferMyList> ce, Object tag) {
        int number = ce.getNumber();
        boolean last = ce.getLast();

        List<OfferMyList> goodsItems = ce.getContent();

        pageNum = number;
        if (number == 0) {
            mGoods.clear();
        }

        if (goodsItems != null && goodsItems.size() > 0) {
            mGoods.addAll(goodsItems);
            loadMoreDelegate.addLoadItemOnly(mGoods);
            //最后一个
            if (last) {
                loadMoreDelegate.setStatusNoMore();
                //loadMoreDelegate.setStatusNormal();
            } else {
                loadMoreDelegate.setStatusNormal();
            }
            loadGoodsContent();
            mGoodsAdapter.notifyDataSetChanged();
            timerStart();
        } else {//没有数据
            loadGoodsEmpty();
            timerStop();
        }
    }

    protected void loadGoodsError() {
        if (mGoods.size() == 0)
            msvGoods.showError();
    }

    protected void loadGoodsEmpty() {
        rightbtn.setVisibility(View.GONE);
        msvGoods.showEmpty();
        msvGoods.getmEmptyView().findViewById(R.id.tv_home_often_go).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(0x0404);
                finish();
            }
        });
    }

    protected void showGoodsLoading() {
        if (mGoods.size() == 0) {
            msvGoods.showLoading();
        } else {
            msvGoods.showContent();
        }
    }

    protected void loadGoodsContent() {

        msvGoods.showContent();

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

    private void reqGoodsList(int pageNumber) {

        RequestEntityMap requestEntityMap = new RequestEntityMap();
        requestEntityMap.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_offer_findMyProductOffer);
        requestEntityMap.putParameter("pageNumber", pageNumber);
        requestEntityMap.putParameter("pageSize", 10);
        request(requestEntityMap, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_offer_findMyProductOffer, onGoodsRequestListener);
    }

    private OnRequestListener<ContentEntity<OfferMyList>> onGoodsRequestListener = new OnRequestListener<ContentEntity<OfferMyList>>() {
        @Override
        public ContentEntity<OfferMyList> jsonToObj(String responseStr) {

            return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, OfferMyList.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();

            ptrFrameLayout.refreshComplete();

            loadGoodsError();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            ptrFrameLayout.refreshComplete();
            loadGoodsError();
        }

        @Override
        public void onStart(Object tag) {
            if(freshFlag) {
                showGoodsLoading();
            }else{
                showProgressDialog();
                showGoodsLoading();
            }
            freshFlag = false;
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<OfferMyList>> response, Object tag) {
            hideProgressDialog();
            ptrFrameLayout.refreshComplete();
            if (response != null) {
                ContentEntity<OfferMyList> responseElement = response.getResponseElement();
                rightbtn.setVisibility(View.VISIBLE);
                updateGoodsList(responseElement, tag);
            }
        }
    };

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            ivBack.performClick();
        }
        return false;
    }



    public void openDialog(final OfferMyList cartGood) {

        final Dialog dialog = new Dialog(this, R.style.no_title_dialog);

        dialog.setContentView(R.layout.dialog_cart_add);
        ImageView ivAdd = (ImageView) dialog.findViewById(R.id.iv_add);
        ImageView ivRemove = (ImageView) dialog.findViewById(R.id.iv_remove);

        final EditText ed = (EditText) dialog.findViewById(R.id.ed_price);

        ed.setText(FormatUtil.subZeroAndDot(cartGood.getCount() + ""));
        ed.setSelection(ed.length());
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 999999;
        ed.setFilters(new InputFilter[]{cashierInputFilter});
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = ed.getText().toString();
                double min = cartGood.getMoq();
                double incr = cartGood.getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                double amount = cnt;


                if (FormatUtil.remainderZero(amount, cartGood.getInventory()) > 0) {
                    amount = cartGood.getInventory();
                }

                amount = FormatUtil.countAdd(amount, incr);
                if (FormatUtil.remainderZero(amount, cartGood.getInventory()) > 0) {
                    amount = cartGood.getInventory();
                }


                cartGood.setShoppingCarProductCount(amount);
                ed.setText(FormatUtil.subZeroAndDot(amount + ""));
                ed.setSelection(ed.length());
            }
        });
        ivRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = ed.getText().toString();
                double min = cartGood.getMoq();
                double incr = cartGood.getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                double amount = cnt;
                if (amount < cartGood.getMoq()) {
                    amount = cartGood.getMoq();
                }

                amount = FormatUtil.countSubtract(amount, incr);
                if (amount < cartGood.getMoq()) {
                    amount = cartGood.getMoq();
                }
                cartGood.setShoppingCarProductCount(amount);
                ed.setText(FormatUtil.subZeroAndDot(amount + ""));
                ed.setSelection(ed.length());
            }
        });
        dialog.findViewById(R.id.negativeButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) OfferMyActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.positiveButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                double productCount = cartGood.getCount();
                String s = ed.getText().toString();
                double min = cartGood.getMoq();
                double incr = cartGood.getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                if (cnt < 0.01 || cnt < min) {
                    T.toast("不能少于" + FormatUtil.subZeroAndDot(min + ""));
                    cnt = FormatUtil.countFormat(cnt, incr, min);
                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }


                if (cnt > cartGood.getInventory()) {
                    T.toast("超过库存");
                    cnt = FormatUtil.countFormat(cartGood.getInventory(), incr, min);

                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }
                incr = incr < 0.01 ? min : incr;

                if (FormatUtil.isRemainder(cnt, incr, min)) {
                    cnt = FormatUtil.countFormat(cnt, incr, min);
                    Log.e("cnt:", "cnt:" + FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }

//                cartGood.setShoppingCarProductCount(cnt);
                reqCartCnt(cnt, cartGood);
                mGoodsAdapter.notifyDataSetChanged();
                InputMethodManager imm = (InputMethodManager) OfferMyActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
                dialog.dismiss();
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {

            }
        });

        dialog.show();

    }

    public void addCartCnt(View v,OfferMyList goods, boolean isAdd) {
        double min = goods.getMoq();
        double incr = goods.getIncr();
        double amount = goods.getCount();


        if (isAdd) {
            amount = FormatUtil.countAdd(amount, incr);
        } else {
            amount = FormatUtil.countAdd(amount, -incr);
        }

        if (FormatUtil.remainderZero(amount, goods.getInventory()) > 0) {
            amount = goods.getInventory();
            T.toast("库存不够");
        }else{
            if(isAdd)
                addAnim(v);
        }
        if (isAdd && FormatUtil.remainderZero(amount, goods.getMoq()) < 0) {
            amount = min;
        }


        if (!isAdd && (FormatUtil.remainderZero(amount, 0) <= 0 || FormatUtil.remainderZero(amount, min) < 0)) {
            amount = 0;
            reqCartCnt(amount, goods);
            return;
        }

//        amount = FormatUtil.countFormat(amount, incr, min);
        amount = FormatUtil.countFormat(amount, incr, min, goods.getInventory());
        reqCartCnt(amount, goods);

    }
    // instanceof HomeGoodsOften.ContentBean)
    public void reqCartCnt(double productCount, OfferMyList goods) {
        if (goods == null) {
            return;
        }

        goods.setShoppingCarProductCount(productCount);
        mGoodsAdapter.notifyDataSetChanged();

        if (!cartHelper.checkIsCartRequesting(goods)) {
            updateCartCnt(productCount, goods);
        } else {

        }
    }
    CartHelper cartHelper = new CartHelper();

    public void responseCartCnt(boolean isFail, OfferMyList goods, double cnt) {
        if (isFail) {
            cartHelper.responseCartFail(goods);
        } else {
            cartHelper.responseCartSuccess(goods, cnt);
        }
    }

    public void updateCartCnt(double productCount, OfferMyList goods) {
        double count = goods.getShoppingCarProductCount();

        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_add);
        re.putParameter("promotionItemId", goods.getPromotionItemId());
        re.putParameter("shoppingCarId", goods.getShoppingCarId());
        re.putParameter("productUnitPrice", goods.getOldPrice());
        re.putParameter("productId", goods.getProductId());
        //re.putParameter("salesType", goods.getType());
        re.putParameter("versionId", goods.getLastSnapshotId());
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("productCount", productCount);
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());

        RequestTag tag = new RequestTag();
        tag.tag = goods;
//        tag.tag = "appOrder/updateShoppingCarProductCount";
        tag.arg1 = productCount + "";
        tag.arg2 = count;
//        tag.arg2 = goods;
        if (cartHelper != null && goods !=null){
            cartHelper.updateRequest(goods.getUniqueKey());
        }
        request(re, tag, onCntRequestListener);
    }

    OnRequestListener<AddCarResponse> onCntRequestListener = new OnRequestListener<AddCarResponse>() {
        @Override
        public AddCarResponse jsonToObj(String s) {
            return new Gson().fromJson(s, AddCarResponse.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
            RequestTag tag = null;
            if (o1 instanceof RequestTag) {
                tag = (RequestTag) o1;
                String arg1 = tag.arg1;
                Object arg2 = tag.arg2;
                Object o2 = tag.tag;
                if (arg1 != null && o2 != null && o2 instanceof OfferMyList) {
                    OfferMyList goods = (OfferMyList) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (arg2 != null && arg2 instanceof Double) {
//                        goods.setShoppingCarProductCount((Double) arg2);
                        responseCartCnt(true, goods, -1);
                        mGoodsAdapter.notifyDataSetChanged();

                        T.toast(goods.getTitle() + " 添加购物车失败");
                    }
                }
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            hideProgressDialog();
            RequestTag tag = null;
            if (i / 10 == 40) {
                T.toast(o + "");
            }
            if (o1 instanceof RequestTag) {
                tag = (RequestTag) o1;
                String arg1 = tag.arg1;
                Object arg2 = tag.arg2;
                Object o2 = tag.tag;
                if (arg1 != null && o2 != null && o2 instanceof OfferMyList) {
                    OfferMyList goods = (OfferMyList) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (arg2 != null && arg2 instanceof Double) {
//                        goods.setShoppingCarProductCount((Double) arg2);
                        responseCartCnt(true, goods, -1);
                        mGoodsAdapter.notifyDataSetChanged();

                        if (i / 100 != 4) {
                            T.toast(goods.getTitle() + " 添加购物车失败");
                        }
                    }
                }
            }
        }

        @Override
        public void onStart(Object o) {
            //showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<AddCarResponse> responseEntity, Object o) {
            hideProgressDialog();
            DataManager.getInstance().oftenListReFresh = true;
            AddCarResponse responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {

                RequestTag tag = null;
                if (o instanceof RequestTag) {
                    tag = (RequestTag) o;
                    String arg1 = tag.arg1;
                    Object o2 = tag.tag;
                    if (arg1 != null && o2 != null && o2 instanceof OfferMyList) {
                        OfferMyList goods = (OfferMyList) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                        //goods.setShoppingCarProductCount(responseElement.getProductCnt());
                        goods.setShoppingCarId(responseElement.getShoppingCarId());
                        DataManager.getInstance().setCartCntStatus(responseElement.getshoppingCarCnt());

                        responseCartCnt(false, goods, responseElement.getProductCnt());
                        if (carCntResponse == null) {
                            mGoodsAdapter.notifyDataSetChanged();
                        } else {
                            carCntResponse.putCategoryCount(responseElement.getCategoryId(), responseElement.getCategoryCnt());
                            carCntResponse.putTopCategoryCount(responseElement.getTopCategoryId(), responseElement.getTopCategoryCnt());
                            carCntResponse.putPromotionCount(responseElement.getTopCategoryId(), responseElement.getPromotionCnt());
                            carCntResponse.putGoodsCount(goods.getIdPlus(), goods.getCount());
                            carCntResponse.putShopingCarId(goods.getIdPlus(), responseElement.getShoppingCarId());
                            if(responseElement.getProductCnt()==0){
                                carCntResponse.getMerMsgMap().remove(responseElement.getShoppingCarId());
                            }
                            updateCnt();
                        }
                    }
                }


            }
        }
    };

/*    View shoppingCartView;
    ViewGroup mainLayout;*/
//    View lvCart;
CarCntResponse carCntResponse;

    public void updateCnt() {

        if (carCntResponse != null) {

            if (mGoods != null) {
                for (int i = 0; i < mGoods.size(); i++) {

                    if(mGoods.get(i) instanceof OfferMyList ){
                        OfferMyList bean = (OfferMyList)mGoods.get(i);
                            if (cartHelper != null && cartHelper.isRequesting(bean.getUniqueKey())) {
                                Log.e("continue", "cnt:down");
                                continue;
                            }else {
                            }
                            bean.setShoppingCarProductCount(carCntResponse.getGoodsCount(bean.getIdPlus()));
                            //Log.e("listGoods", "cnt:" + item.getCount() + "---id:" + item.getId());
                            bean.setShoppingCarId(carCntResponse.getShopingCarId(bean.getIdPlus()));
                        }


                    }
                }

            if (mGoodsAdapter != null) {
                mGoodsAdapter.notifyDataSetChanged();
            }
        }

    }



/*    private void initCartView() {
        AppActivity appActivity = this;
        if (appActivity instanceof HomeActivity) {
            shoppingCartView = ((HomeActivity) appActivity).getCartView();
            mainLayout = ((HomeActivity) appActivity).getMainView();
//            lvCart = lvProduct;
        }
    }*/


    public void addAnim(View view) {
        int[] addLocation = new int[2];
        int[] cartLocation = new int[2];
//        int[] lvCartLocation = new int[2];
        view.getLocationInWindow(addLocation);
        righticon.getLocationInWindow(cartLocation);
//        lvCart.getLocationInWindow(lvCartLocation);

        PointF startP = new PointF();
        PointF endP = new PointF();
        PointF controlP = new PointF();

        startP.x = addLocation[0];
        startP.y = addLocation[1];
        endP.x = cartLocation[0] + LocalDisplay.dp2px(10);
        endP.y = cartLocation[1] - this.getResources().getDimensionPixelSize(R.dimen.bottom_nav_ic_height);
        controlP.x = endP.x;
        controlP.y = startP.y;

        final FakeAddImageView fakeAddImageView = new FakeAddImageView(this);
        rl_main_layout.addView(fakeAddImageView);
        fakeAddImageView.setImageResource(R.drawable.cart_bezier);
        fakeAddImageView.getLayoutParams().width = LocalDisplay.dp2px(10);
        fakeAddImageView.getLayoutParams().height = LocalDisplay.dp2px(10);
        fakeAddImageView.setVisibility(View.VISIBLE);
        ObjectAnimator addAnimator = ObjectAnimator.ofObject(fakeAddImageView, "mPointF",
                new PointFTypeEvaluator(controlP), startP, endP);
        addAnimator.setInterpolator(new AccelerateInterpolator());
        addAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                fakeAddImageView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                fakeAddImageView.setVisibility(View.GONE);
                rl_main_layout.removeView(fakeAddImageView);
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        ObjectAnimator scaleAnimatorX = new ObjectAnimator().ofFloat(righticon, "scaleX", 0.6f, 1.0f);
        ObjectAnimator scaleAnimatorY = new ObjectAnimator().ofFloat(righticon, "scaleY", 0.6f, 1.0f);
        scaleAnimatorX.setInterpolator(new AccelerateInterpolator());
        scaleAnimatorY.setInterpolator(new AccelerateInterpolator());
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(scaleAnimatorX).with(scaleAnimatorY).after(addAnimator);
        animatorSet.setDuration(340);
        animatorSet.start();
    }

    public void requestFreshItem(final OfferMyList goods) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_offer_findMyProductOffer);
        re.putParameter("productOfferDetailsId", goods.getProductOfferDetailsId());
        request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_offer_findMyProductOffer, new OnRequestListener<ContentEntity<OfferMyList>>() {
            @Override
            public ContentEntity<OfferMyList> jsonToObj(String responseStr) {

                return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, OfferMyList.class);
            }
            @Override
            public void onFail(int i, Object o, Object o1) {
                hideProgressDialog();
            }

            @Override
            public void onResponseError(int i, Object o1, Object o) {
                hideProgressDialog();
            }

            @Override
            public void onStart(Object o) {
                //showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<ContentEntity<OfferMyList>> responseEntity, Object o) {
                hideProgressDialog();
                ContentEntity<OfferMyList> bean = responseEntity.getResponseElement();

                if(bean==null||bean.getResponse()==null||bean.getResponse().get(0)==null||bean.getResponse().get(0).getStatus()==1){
                    return;
                }
                goods.setStatus(bean.getResponse().get(0).getStatus());
                goods.setOfferDuration(bean.getResponse().get(0).getOfferDuration());
                goods.setOverTime(bean.getResponse().get(0).getOverTime());
                goods.setOfferTime(bean.getResponse().get(0).getOfferTime());
                goods.setPrice(bean.getResponse().get(0).getPrice());
                goods.setOfferStatusCopy(bean.getResponse().get(0).getOfferStatusCopy());
                mGoodsAdapter.notifyItemChanged(mGoods.indexOf(goods));
            }
        });

    }

}
